<template>
<div class="entering-wrap">
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" />
    <div class="header-title" v-if="type == 0">
      <div class="shadow" @click="type = 1;navLeftText='返回上一步'">
            <svg slot="icon" class="icon closeImg" aria-hidden="true" style="font-size: 2.5rem;margin-right: 4px;">
                    <use xlink:href="#icon-kaidian"></use>
              </svg>
            <h3 >
             &nbsp;我要开店&nbsp;
            </h3>
        </div>
        <div class="shadow" @click="type = 2;navLeftText='返回上一步'">
            <svg slot="icon" class="icon closeImg" aria-hidden="true" style="font-size: 2.5rem;margin-right: 4px;">
                <use xlink:href="#icon-fendianchang"></use>
            </svg>
            <h3>
                &nbsp;成为店长&nbsp;
            </h3>
        </div>
        
    </div>
    <div v-if="type == 1">
        <div>
            <van-steps :active="active">
                <van-step>申请入驻</van-step>
                <van-step>入驻审核</van-step>
                <van-step>审核通过</van-step>
            </van-steps>
        </div>
        <div class="contain">
            <van-cell-group>
                <van-field v-model="store.name" required clearable label="商户名称" placeholder="请输入商户名称" />
                <van-field readonly clickable label="主营项目" :value="itemRadio" placeholder="请选择主营项目" @click="showPicker = true" />
                <van-popup v-model="showPicker" position="bottom">
                    <van-picker show-toolbar :columns="columnsText" @cancel="showPicker = false" @confirm="onConfirm" />
                </van-popup>
                <van-field v-model="store.mobile" label="手机号" type="number" placeholder="请输入手机号" />
                <van-field v-model="store.contact" required clearable label="联系人" placeholder="请输入联系人姓名" />
            </van-cell-group>
            <van-radio-group v-model="radio">
                <van-cell-group style="margin-top: 10px;">
                    <van-cell title="免费商铺" @click="radio = '0';enteringText='立即申请'">
                        <van-radio slot="right-icon" name="0" />
                    </van-cell>
                    <van-cell title="分店" @click="radio = '1'">
                        <van-radio slot="right-icon" name="1" />
                    </van-cell>
                </van-cell-group>
            </van-radio-group>
        </div>
        <p class="title">请上传营业执照</p>
        <div class="file">
            <van-uploader :after-read="afterRead" preview-size="160px" :max-count="1">
                <img v-if="fileList.url" :src="fileList.url" style="width: 160px;height: 160px;">
                <van-icon v-else name="plus" size="4.4rem" style="line-height: 160px;" />
            </van-uploader>
        </div>
        <van-button :disabled="btndisabled" class="sub" @click="submitStore" :type="btndisabled ? 'warning ' : 'primary'" size="large">{{ enteringText }}</van-button>
    </div>
    <div v-if="type == 2">
        <div class="text-center" style="margin-top: 10rem">
            <van-button plain type="primary" @click="getManager">成为店长</van-button>
        </div>
    </div>

    <van-popup v-model="payShow" position="bottom" closeable :style="{ height: '40%' }">
        <van-cell-group title="请选择支付方式">
            <van-cell title="微信支付" @click="getPay(1)" />
        </van-cell-group>
    </van-popup>
</div>
</template>

<script>
import {
    Notify,
    Popup,
    Toast
} from 'vant';
import wx from 'weixin-js-sdk'
export default {
    name: 'Entering',
    data() {
        return {
            type: 0,
            image_id: null,
            active: 0,
            btndisabled: true,
            showPicker: false,
            columns: null,
            columnsText: null,
            store: {
                name: '',
                item: '',
                mobile: '',
                contact: ''
            },
            fileList: {
                url: false
            },
            radio: '0',
            itemRadio: '综合类',
            parent_id: null,
            payShow: false,
            payType: '0',
            enteringText: '立即申请',
            // navLeftText:'',
            mode:null,
            c_mode_type: null
        };
    },
    created() {
        if(this.$route.query.type == 1){
            this.type = 1
            this.mode = 1
        }
        this.parent_id = this.$route.params.store_parent_id || sessionStorage.getItem('shareStoreParentId');
        this.getColumnsdata();
    },
    methods: {
        onClickLeft() {
            if(this.type == 0){
                this.$router.push({name:'mine'})
            }else if(this.mode = 1){
                this.$router.push({name:'mine'})
            }else {
                this.type = 0
            }
        },
        getColumnsdata(){
            this.axios.get('/api/store/admin/type/data').then(r=>{
                this.columns = r.data.data;
                let arr = [];
                r.data.data.forEach(element => {
                    arr.push(element.title)
                });
                this.columnsText = arr;
                
                this.c_mode_type = r.data.data[0].id
            }).catch(()=>{
                this.$notify('加载错误');
            })
        },
        phoneNum(){
            let r = true;
            var phone = this.store.mobile;
            if(!(/^1[3456789]\d{9}$/.test(phone))){   
                r = false
            }
            return r
        },
        afterRead(file) {
            Toast.loading({
                mask: this.btndisabled ? false : true,
                message: '识别中...'
            });
            this.fileList.url = file.content;
            let token = sessionStorage.getItem("token");
            let params = new FormData();
            params.append("image", file.file);
            params.append("token", token);
            this.axios.post('/api/store/manager/business_license', params).then(res => {
                if (res.data.code == 200) {
                    this.image_id = res.data.data.id;
                    Notify({
                        type: 'success',
                        message: res.data.message
                    });
                    this.btndisabled = false
                } else {
                    Notify({
                        type: 'error',
                        message: res.data.message
                    });
                    this.btndisabled = true
                }
            }).catch(error => {
                this.btndisabled = true;
                Notify({
                    type: 'error',
                    message: error.message
                });
            });
        },
        removeURLParameter(url, parameter) {
            var urlparts = url.split('?');
            if (urlparts.length >= 2) {
                //参数名前缀
                var prefix = encodeURIComponent(parameter) + '=';
                var pars = urlparts[1].split(/[&;]/g);
                //循环查找匹配参数
                for (var i = pars.length; i-- > 0;) {
                    if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                        //存在则删除
                        pars.splice(i, 1);
                    }
                }
                return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
            }
            return url;
        },
        getManager(){
          let params = {};
          params.token = sessionStorage.getItem("token")
          this.axios.get('/api/store/user/clerk/'+'wechat',{params}).then(res=>{
            this.wxPay(res.data.data);
          }).catch(err=>{
            console.log(err); 
          })
        },
        submitStore(){
        let mode = null;
        if(this.radio == '0'){
            mode = 'free'
        }else {
            mode = 'vip'
        }
        if(this.phoneNum()){
            this.axios.post('/api/store/user/apply', {
            title: this.store.name,
            realname: this.store.contact,
            mobile: this.store.mobile,
            token: sessionStorage.getItem("token"),
            store_type: this.c_mode_type,
            certificate_id: this.image_id,
            mode: mode
            }).then(res => {
                if (res.data.code == 200) {
                    this.$router.go(-1);
                    Notify({
                        type: 'success',
                        background: '#07c160',
                        message: res.data.message
                    });
                } else {
                    Notify({
                        type: 'success',
                        background: '#07c160',
                        message: res.data.message
                    });
                }
            }).catch(error => Notify({
                type: 'error',
                message: error.message
            }))
        }else {
            this.$toast('手机号码填写错误,请检查')
        }
        
        
            
        },
        getPay(e){
          let payType = '';
          if(e == 0){}else {
            payType = 'wechat'
          }
          this.axios.post('api/store/user/apply/'+payType, {
                title: this.store.name,
                realname: this.store.contact,
                mobile: this.store.mobile,
                token: sessionStorage.getItem("token"),
                store_type: this.c_mode_type,
                certificate_id: this.image_id,
                parent_id: this.parent_id,
                mode: 'vip'
            }).then(res => {
              this.wxPay(res.data.data)
                if (res.data.code == 200) {
                    // this.$router.go(-1);
                    Notify({
                        type: 'success',
                        background: '#07c160',
                        message: res.data.message
                    });
                } else {
                    Notify({
                        type: 'success',
                        background: '#07c160',
                        message: res.data.message
                    });
                }
            }).catch(error => Notify({
                type: 'error',
                message: error.message
            }))
        },
        onConfirm(value,index) {
            this.c_mode_type = this.columns[index].id;
            this.itemRadio = value;
            this.showPicker = false;
        },
        wxPay(data) {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function () {
                wx.chooseWXPay({
                    timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                    package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: data.paySign, // 支付签名
                    success: function (res) {
                        // 支付成功后的回调函数
                        if (res.errMsg == "chooseWXPay:ok") {
                            Dialog({
                                message: '支付成功'
                            });
                        } else {
                            Dialog({
                                message: '错误'
                            });
                        }
                    },
                    error: function () {
                        Dialog({
                            message: '支付失败'
                        });
                    },
                    cancel: function () {
                        Dialog({
                            message: '取消支付'
                        });
                    }
                });
            });
        }
    }
}
</script>

<style scoped>
.entering-wrap {
    padding-bottom: 70px;
}

.header-title {
    position: fixed;
    top: 46px;
    right: 0;
    left: 0;
    bottom: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    justify-content: center;
    align-items: end;
}

.header-title div {
    padding: 1.5rem .5rem .5rem;
    background: white;
    text-align:center
}

.title {
    text-align: center
}

.contain {
    margin-top: 10px
}

.file {
    margin: auto;
    width: 160px;
    text-align: center;
}

.sub {
    position: relative
}

.sub {
    background: red;
    border: none;
    color: white;
    width: 100%;
    height: 57px;
    position: fixed;
    bottom: 0
}
</style>
